//
//  ByCoreToolFileHandler.m
//  beibei_ios
//
//  Created by mc on 16/4/23.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByCoreToolFileHandler.h"
#define FileManager [NSFileManager defaultManager]
#define DocumentPath [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
@implementation ByCoreToolFileHandler
/**
 *  文件的创建以及写入
 */
+(void)createFile:(NSString *)fileName andContents:(NSString *)content{
    //文件路径
    NSString *filePath = [DocumentPath stringByAppendingPathComponent:fileName];
    //判断文件是否存在
    if (![FileManager fileExistsAtPath:filePath]) {
          //如果不存在就创建，存在不会覆盖
        [content writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:nil];
    }else{
        NSFileHandle *fileHander = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
        [fileHander seekToEndOfFile];
        NSData *stringData = [content dataUsingEncoding:NSUTF8StringEncoding];
        [fileHander writeData:stringData];
        [fileHander closeFile];
    }
}

/**
 *  文件的删除
 */
+ (void)deleteFile:(NSString *)fileName{
     NSString *filePath = [DocumentPath stringByAppendingPathComponent:fileName];
    //判断文件是否存在
    BOOL isExist = [FileManager fileExistsAtPath:filePath];
    if (isExist) {
        BOOL isDelete = [FileManager removeItemAtPath:filePath error:nil];
        if (isDelete) {
            NSLog(@"delete success.....");
        }else{
            NSLog(@"delete failure.....");
        }
    }
    NSLog(@"%@",filePath);
}

/**
 *  文件内容的读取
 */
+(NSString *) readFile:(NSString *) fileName{
    NSString *filePath = [DocumentPath stringByAppendingPathComponent:fileName];
    NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    return content;
}

/**
 *  获取文件的大小
 */
+(float)fetchFileSize:(NSString *)fileName{
    NSString *filePath = [DocumentPath stringByAppendingPathComponent:fileName];
    if ([FileManager fileExistsAtPath:filePath]) {
        return [[FileManager attributesOfItemAtPath:filePath error:nil] fileSize]/(1024.0*1024);
    }
    return 0;
//    NSDictionary *fileDic = [FileManager attributesOfItemAtPath:filePath error:nil];
//    NSNumber *fileSize = [fileDic objectForKey:NSFileSize];

}
/**
 *  文件重命名
 */
+(void)renameFile:(NSString *)newFileName :(NSString *)oldFileName{
   //通过移动该文件对文件重命名
//    NSString *filePath = [DocumentPath stringByAppendingPathComponent:newFileName];
    //判断是否移动
//    if ([FileManager moveItemAtPath:<#(nonnull NSString *)#> toPath:<#(nonnull NSString *)#> error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>]) {
//        <#statements#>
//    }
    

}
@end
